package com.ldy.db;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import com.ldy.annotation.Table;
import com.ldy.test.Model;
import com.ldy.test.Student;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SqliteHelper extends SQLiteOpenHelper {

	private final static String dbName = "test_db.db";

	private final static int version = 1;

	public SqliteHelper(Context context) {
		super(context, dbName, null, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(createTable(Model.class));
		db.execSQL(createTable(Student.class));
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	/**
	 * 将java数据类型转换成数据库的数据类型
	 * 
	 * @param type
	 * @return
	 */
	private String javaType2DBtype(String type) {

		if (type == null || type.toLowerCase().equals("null")) {
			return "NULL";
		}

		if (type.equals("int")) {
			return "INTEGER";
		}

		if (type.endsWith("String")) {
			return "TEXT";
		}

		if (type.endsWith("Date") || type.toLowerCase().endsWith("long")) {
			return "LONG";
		}

		return type;
	}

	private String createTable(Class clz) {
		// Class clz = Model.class;
		// 获取类的注解
		Annotation[] anno = clz.getAnnotations();
		String tableName = null;
		if (anno.length > 0 && anno[0] instanceof Table) {
			Table table = (Table) anno[0];
			tableName = table.tableName();
			if (tableName.equals("")) {
				tableName = clz.getSimpleName();
			}
		}

		// 获取属性的注解
		Field[] fields = clz.getDeclaredFields();
		StringBuilder builder = new StringBuilder();
		String table = "CREATE TABLE IF NOT EXISTS " + tableName + " (";
		builder.append(table);
		for (Field field : fields) {
			Annotation fieldAnno = field.getAnnotation(com.ldy.annotation.Field.class);
			if (fieldAnno instanceof com.ldy.annotation.Field) {
				com.ldy.annotation.Field f = (com.ldy.annotation.Field) fieldAnno;
				String fieldName = f.columnName();
				if (fieldName.equals("")) {
					fieldName = field.getName();
				}

				if (f.generatedId() && f.id()) {
					throw new IllegalArgumentException("不能同时设置为主键");
				}

				if (f.generatedId()) {
					builder.append(fieldName + " " + javaType2DBtype(field.getType().getName()) + " PRIMARY KEY AUTOINCREMENT ,");
				}

				if (f.id()) {
					builder.append(fieldName + " " + javaType2DBtype(field.getType().getName()) + " PRIMARY KEY ,");
				}

				String sql = builder.toString();
				if (sql.indexOf(fieldName) == -1) {
					builder.append(fieldName + " " + javaType2DBtype(field.getType().getSimpleName()) + ",");
				}
			}
		}
		builder.append(")");
		builder.delete(builder.length() - 2, builder.length() - 1);
		Log.i("data", "sql:" + builder.toString());
		return builder.toString();
	}
}
